package com.heihx.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heihx.context.BaseContext;
import com.heihx.entity.AddressBook;
import com.heihx.mapper.AddressBookMapper;
import com.heihx.service.AddressBookService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        Long userId = addressBook.getUserId();
        String phone = addressBook.getPhone();
        Integer isDefault = addressBook.getIsDefault();
        return lambdaQuery()
                .eq(userId != null, AddressBook::getUserId, userId)
                .like(StringUtils.isNotBlank(phone), AddressBook::getPhone, phone)
                .eq(isDefault != null, AddressBook::getIsDefault, isDefault)
                .list();
    }

    @Override
    public void saveWithUserId(AddressBook addressBook) {
        log.info("用户id:{}",BaseContext.getCurrentId());
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        save(addressBook);
    }

    @Override
    @GlobalTransactional
    public void setDefault(AddressBook addressBook) {
        //将当前用户所有地址改为非默认
        lambdaUpdate()
                .set(AddressBook::getIsDefault, 0)
                .eq(AddressBook::getUserId, 1)
                .update();

        addressBook.setIsDefault(1);
        addressBook.setUserId(1L);
        lambdaUpdate()
                .set(AddressBook::getIsDefault, 1)
                .eq(AddressBook::getId, addressBook.getId())
                .update();
    }
}
